import os

from flask_wtf import FlaskForm
from flask_wtf.file import FileField, FileAllowed
from wtforms import StringField, PasswordField, SubmitField, IntegerField, TextAreaField, MultipleFileField
from wtforms.validators import Required, Length, EqualTo, Email
from wtforms.validators import ValidationError

from app.models import User
from config import Config

# 注销账户请求表单
class DeleteAccountRequestForm(FlaskForm):
    submit = SubmitField("继续")


# 注销账户表单
class DeleteAccountForm(FlaskForm):
    code = IntegerField("邮箱验证码", validators=[Required()]) 
    password = PasswordField("密码", validators=[Required()])
    submit = SubmitField("确定注销账户")

# 用户信息设置表单
class UserSetInfoForm(FlaskForm):
    username = StringField("修改用户名")
    intro = StringField("修改介绍")
    avatar_img_url = FileField("修改头像", validators=[FileAllowed(Config.IMG_FILE_NAME_EXT, "文件不合法")])

    submit = SubmitField("提交修改")

    def __init__(self, user, **kwargs):
        super().__init__(**kwargs)
        self.username.render_kw = {"placeholder": user.username}
        self.intro.render_kw = {"placeholder": user.intro}

    def validate_username(self, field):
        username = field.data.strip()
        if len(username) == 0:
            self.username.data = self.username.render_kw["placeholder"]

    def validate_intro(self, field):
        intro = field.data.strip()
        if len(intro) == 0:
            self.intro.data = self.intro.render_kw["placeholder"]

# 邮箱换绑请求表单
class ClickSendEmailCodeForm(FlaskForm):
    submit1 = SubmitField("点击发送邮件验证码")

# 邮箱换绑表单
class EmailChangeForm(FlaskForm):
    code = IntegerField("邮箱验证码", validators=[Required()])
    email = StringField("新的邮箱", validators=[Required(), Email("邮箱非法")])
    submit2 = SubmitField("确定修改")

    def validate_email(self, field):
        email = field.data
        if User.query.filter_by(email=email, deleted="false").first():
            raise ValidationError("邮箱已经注册")

# 密码修改表单
class PasswordChangeForm(FlaskForm):
    old_password = PasswordField("旧密码", validators=[Required(), Length(8, 64, "最小长度为8 最大长度为64")])
    new_password = PasswordField("新密码", validators=[Required(), Length(8, 64, "最小长度为8 最大长度为64")])
    confirm = PasswordField("确认密码", validators=[Required(), EqualTo("new_password", "两次密码不一致")])
    submit2 = SubmitField("确定修改")

# 动态发布表单
class PostForm(FlaskForm):
    body = TextAreaField("不少于15个字符的内容", validators=[Required(), Length(15,message="最少要有15个字符")])
    submit = SubmitField("发布")

    def validate_body(self, field):
        self.body.data = field.data.replace("\r\n"," ").replace("\n"," ")

# 用户图片上传表单
class UserImagesUploadsForm(FlaskForm):
    images = MultipleFileField("上传图片", validators=[Required()])
    submit = SubmitField("确认上传")

    def validate_images(self, imgs):
        f =  imgs.data[0]
        if f.filename == "":
            raise ValidationError("你应该先选择图片！")
        for img in imgs.data:
            if os.path.splitext(img.filename)[1][1:] not in Config.IMG_FILE_NAME_EXT:
                self.images.data = []
                raise ValidationError("有文件不合法")

# 用户提权请求表单
class UserArticlePermissionRequestForm(FlaskForm):
    title = StringField("标题")
    text = TextAreaField("申请理由", validators=[Required()])
    submit = SubmitField("提交")

    def __init__(self, user, **kwargs):
        self.user = user
        super().__init__(**kwargs)
        self.title.render_kw = {"placeholder": "申请成为作者"}

    def validate_title(self, field):
        title = field.data
        if title == "":
            self.title.data = self.title.render_kw["placeholder"]

# 用户撰写文章表单
class UserArticleWriteForm(FlaskForm):
    title = StringField("文章标题", validators=[Required()])
    cover_img = FileField("文章封面")
    tags = StringField("文章标签，多个使用英文分号分隔，单个不能超过16字符")
    abstract = TextAreaField("文章摘要", validators=[Required()])
    content = TextAreaField("正文", validators=[Required()])
    draft = SubmitField("保存草稿")
    submit = SubmitField("保存发布")

    def validate_abstract(self, field):
        if len(field.data) > 255:
            raise ValidationError("最大字数为255")

# 用户文章草稿编辑表单
class UserArticleSetForm(FlaskForm):
    title = StringField("文章标题", validators=[Required()])
    cover_img = StringField("文章封面")
    tags = StringField("文章标签，多个使用英文分号分隔")
    abstract = TextAreaField("文章摘要", validators=[Required()])
    content = TextAreaField("正文", validators=[Required()])
    draft = SubmitField("保存草稿")
    submit = SubmitField("保存发布")

    def validate_abstract(self, field):
        if len(field.data) > 255:
            raise ValidationError("最大字数为255")
